import json
import socket
import time
import requests
import urllib3

# for InsecureRequestWarning
urllib3.disable_warnings()
socket.setdefaulttimeout(30)


def get_response_json(url):
    headers1 = {
        'Host': 'bigquant.com',
        'Connection': 'keep-alive',
        'Accept': 'application/json, text/plain, */*',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
                      'Chrome/86.0.4240.183 Safari/537.36'
    }
    # 解析json
    try:
        response = requests.get(url=url, headers=headers1, verify=False)
        response_json = json.loads(response.text)
    except:
        try:
            response = requests.get(url=url, headers=headers1, verify=False)
            response_json = json.loads(response.text)
        except:
            try:
                response = requests.get(url=url, headers=headers1, verify=False)
                response_json = json.loads(response.text)
            except Exception:
                print('502 bad gate.URL:', url)
                raise Exception
    return response_json


def get_translated_trade_date(str_1):
    str_1 = str(str_1)
    str_2 = str_1[0:4] + '-' + str_1[4:6] + '-' + str_1[6:]
    return str_2


def get_day(today, day_count):
    # 1 天=86400 秒
    one_day = 86400
    # 某天
    t0_struct = time.strptime(today, '%Y-%m-%d')
    t0_second = time.mktime(t0_struct)

    # n天
    t1_second = t0_second + one_day * day_count
    t1_struct = time.localtime(t1_second)
    t1_str = time.strftime('%Y-%m-%d', t1_struct)
    return t1_str


def get_day_count(bigger_day_str, litter_day_str):
    t1_struct = time.strptime(litter_day_str, "%Y-%m-%d")
    t1_second = time.mktime(t1_struct)

    t0_struct = time.strptime(bigger_day_str, "%Y-%m-%d")
    t0_second = time.mktime(t0_struct)

    one_day = 86400
    day_num = int((t0_second - t1_second) / one_day)
    return day_num
